package base

import (
	"context"
	log "github.com/sirupsen/logrus"
	"net/http"
	_ "net/http/pprof"
	"time"
)

//ini配置例子：
//[pprof]
//enabled=true
//server.port=6060

type PprofStarter struct {
	BaseStarter
	server *http.Server
	addr   string
}

func (s *PprofStarter) Init(ctx StarterContext) {

}

func (s *PprofStarter) Start(ctx StarterContext) {
	conf := ctx.Props()
	if conf.GetBoolDefault("pprof.enabled", false) {
		port := conf.GetDefault("pprof.server.port", "6060")
		s.addr = ":" + port
		s.server = &http.Server{Addr: s.addr, Handler: nil}
		//开启pprof
		go func() {
			log.Infof("starting pprof server for port: %s", port)
			log.Println(s.server.ListenAndServe())
		}()
	}
}

func (s *PprofStarter) Stop(ctx StarterContext) {
	contx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := s.server.Shutdown(contx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Info("gin server shutdown on: ", s.addr)

}
